package pl.lodz.p.browarex.base;

import java.io.Serializable;
import java.util.List;

import pl.lodz.p.browarex.base.interfaces.IBaseModel;
import pl.lodz.p.browarex.base.interfaces.ICrudDao;



public abstract class BaseCrudDao<MODEL extends IBaseModel<ID>, ID extends Serializable> extends BaseDao<MODEL, Serializable> implements ICrudDao<MODEL, ID> {

	/** typ obiektu domenowego. */
	protected final Class<MODEL> type;

	public BaseCrudDao(Class<MODEL> type) {
		if (type == null) {
			throw new IllegalArgumentException("type cannot be null");
		}
		this.type = type;

	}

	public MODEL create(MODEL model) {
		getSession().persist(model);
		return model;
	}
	
	public List<MODEL> list() {
		return getSession().createCriteria(type).list();
	}

	public void delete(ID id) {
		getSession().delete(getSession().load(this.type, id));
	}

	public void delete(MODEL model) {
		getSession().delete(model);
	}

	public boolean exist(ID id) {
		return (getSession().get(this.type, id) != null);
	}

	public MODEL update(MODEL model) {
		getSession().update(model);
		return model;
	}

	public void save(MODEL model) {
		if (model.getId() == null) {
			this.create(model);
		} else {
			getSession().update(model);
		}
	}

	@SuppressWarnings("unchecked")
	public MODEL load(ID id) {
		return (MODEL) getSession().get(this.type, id);
	}

	public void clearSession() {
		getSession().flush();
		getSession().clear();
	}
	
	public void evict(MODEL model) {
		getSession().evict(model);
	}

}